import 'package:flutter/material.dart';

import '../../model/magic_prompt_category_model.dart';
import '../../model/magic_prompt_model.dart';
import '../../model/prompts_model.dart';

///关键词
class InputPromptPage extends StatefulWidget {
  const InputPromptPage({super.key});

  @override
  State<InputPromptPage> createState() => _InputPromptPageState();
}

class _InputPromptPageState extends State<InputPromptPage> {
  final TextEditingController _promptController = TextEditingController();
  int currentCategoryIndex = 0;
  final List<MagicPromptCategoryModel> _categoryList = [
    MagicPromptCategoryModel(id: 0, name: "name0", pid: 0, level: 0),
    MagicPromptCategoryModel(id: 1, name: "name1", pid: 1, level: 1),
    MagicPromptCategoryModel(id: 2, name: "name2", pid: 2, level: 2),
  ];
  List<MagicPromptModel> _magicPromptList = [
    MagicPromptModel(id: 0, name: "Prompt0", prompts: [
      PromptsModel(
          id: 0, prompt: "prompt0", secondCategoryId: 0, selected: false),
      PromptsModel(
          id: 1, prompt: "prompt1", secondCategoryId: 0, selected: false),
      PromptsModel(
          id: 2, prompt: "prompt2", secondCategoryId: 0, selected: false),
    ]),
    MagicPromptModel(id: 1, name: "Prompt1", prompts: [
      PromptsModel(
          id: 3, prompt: "prompt3", secondCategoryId: 1, selected: false),
      PromptsModel(
          id: 4, prompt: "prompt4", secondCategoryId: 1, selected: false),
      PromptsModel(
          id: 5, prompt: "prompt5", secondCategoryId: 1, selected: false),
    ]),
    MagicPromptModel(id: 2, name: "Prompt2", prompts: [
      PromptsModel(
          id: 6, prompt: "prompt6", secondCategoryId: 2, selected: false),
      PromptsModel(
          id: 7, prompt: "prompt7", secondCategoryId: 2, selected: false),
      PromptsModel(
          id: 8, prompt: "prompt8", secondCategoryId: 2, selected: false),
    ]),
  ];

  bool loading = true;

  ///记录分类对应的数据
  final Map<int, List<MagicPromptModel>> _promptMap = {};

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  ///加载分类数据
  _getCategoryForDataById(int id) {
    //先到Map取 没有加载网络
    List<MagicPromptModel>? list = _promptMap[id];
    if (list == null) {
      // _magicPrompt(id);
    } else {
      _magicPromptList = list;
    }
  }

  ///计算每个类型选择的个数
  int _getCategorySelectedCountById(int id) {
    List<MagicPromptModel>? list = _promptMap[id];
    if (list == null) {
      return 0;
    }
    if (list.isEmpty) {
      return 0;
    }

    int count = 0;
    for (int i = 0; i < list.length; i++) {
      list[i].prompts?.forEach((element) {
        if (element.selected!) {
          count++;
        }
      });
    }

    return count;
  }

  ///显示选择的
  _getAllSelect() async {
    String promptsText = "";
    _promptMap.forEach((key, value) {
      for (var ele in value) {
        ele.prompts?.forEach((element) {
          if (element.selected!) {
            promptsText += element.prompt ?? "";
            promptsText += ",";
          }
        });
      }
    });
    _promptController.text = promptsText;
  }

  ///取消选择的
  _cleanSelected() async {
    _promptMap.forEach((key, value) {
      for (var ele in value) {
        ele.prompts?.forEach((element) {
          if (element.selected!) {
            element.selected = false;
          }
        });
      }
    });
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _buildAppBar(),
      body: _buildBody(),
    );
  }

  _buildAppBar() {
    return AppBar(
      backgroundColor: Colors.transparent,
      leading: IconButton(
        onPressed: () {
          Navigator.pop(context);
        },
        icon: Image.asset("assets/images/ic_back.png"),
      ),
      title: Text("Input Prompts",
          style: TextStyle(
              color: Colors.white, fontSize: 17, fontWeight: FontWeight.bold)),
      centerTitle: true,
      actions: [
        ElevatedButton(
            style: ButtonStyle(
                minimumSize: MaterialStateProperty.all(const Size(0, 0)),
                padding: MaterialStateProperty.all(
                    const EdgeInsets.symmetric(horizontal: 19, vertical: 7)),
                backgroundColor:
                    MaterialStateProperty.all(const Color(0xFF608FF4))),
            onPressed: () {
              Navigator.pop(context, _promptController.text);
            },
            child: Text("OK",
                style: TextStyle(
                    color: Colors.white,
                    fontSize: 14,
                    fontWeight: FontWeight.bold))),
        const SizedBox(width: 16)
      ],
    );
  }

  _buildBody() {
    return Stack(
      children: [
        Column(
          children: [
            _buildPrompt(),
            const SizedBox(height: 20),
            Expanded(child: _buildPromptView())
          ],
        ),
        // if (loading) const LoadingView(),
      ],
    );
  }

  /// 关键词描述
  _buildPrompt() {
    return Container(
      padding: const EdgeInsets.all(16),
      margin: const EdgeInsets.symmetric(horizontal: 16),
      decoration: BoxDecoration(
          color: const Color(0xFF070F22),
          border: Border.all(color: const Color(0x994C8EFF), width: 1),
          borderRadius: const BorderRadius.all(Radius.circular(16))),
      child: Column(
        children: [
          TextField(
            enabled: false,
            textAlign: TextAlign.start,
            textInputAction: TextInputAction.done,
            maxLines: 4,
            minLines: 4,
            onChanged: (v) {
              setState(() {});
            },
            controller: _promptController,
            style: TextStyle(color: Colors.white, fontSize: 14),
            decoration: InputDecoration(
              contentPadding:
                  const EdgeInsets.symmetric(horizontal: 0, vertical: 0),
              isDense: true,
              hintText: "",
              hintStyle: TextStyle(
                  color: Colors.white,
                  fontSize: 14,
                  fontWeight: FontWeight.bold),
              enabledBorder: InputBorder.none,
              focusedBorder: InputBorder.none,
            ),
          ),
          const SizedBox(height: 12),
          Row(
            children: [
              GestureDetector(
                onTap: () {
                  //  _imageTemplateRandom();
                },
                child:
                    Image.asset("assets/images/ic_suprise_me.png", height: 20),
              ),
              const Spacer(),
              GestureDetector(
                  onTap: () {
                    setState(() {
                      _promptController.text = "";
                      _cleanSelected();
                    });
                  },
                  child: Image.asset("assets/images/ic_delete_text.png",
                      height: 19)),
            ],
          )
        ],
      ),
    );
  }

  _buildPromptView() {
    return Container(
      padding: const EdgeInsets.only(top: 15),
      decoration: const BoxDecoration(
          color: Color(0xFF1F2C4E),
          borderRadius: BorderRadius.only(
              topRight: Radius.circular(18), topLeft: Radius.circular(18))),
      child: Row(
        children: [
          SizedBox(
            width: 100,
            child: _buildCategoryListView(),
          ),
          const VerticalDivider(color: Color(0xFF172549)),
          const SizedBox(width: 16),
          Expanded(child: _buildPrompts())
        ],
      ),
    );
  }

  ///一级
  _buildCategoryListView() {
    return ListView.builder(
        itemCount: _categoryList.length,
        itemBuilder: (context, index) => _buildCategoryListViewItem(index));
  }

  ///一级item
  _buildCategoryListViewItem(int index) {
    MagicPromptCategoryModel categoryModel = _categoryList[index];

    int count = _getCategorySelectedCountById(categoryModel.id!);

    return Stack(
      clipBehavior: Clip.none,
      children: [
        GestureDetector(
          onTap: () {
            setState(() {
              currentCategoryIndex = index;
              _getCategoryForDataById(categoryModel.id!);
            });
          },
          child: Container(
            color: currentCategoryIndex == index
                ? const Color(0x2E608FF4)
                : Colors.transparent,
            width: 100,
            height: 44,
            child: Row(
              children: [
                Container(
                  width: 4,
                  decoration: BoxDecoration(
                      color: currentCategoryIndex == index
                          ? const Color(0xFF6092F4)
                          : Colors.transparent,
                      borderRadius: const BorderRadius.only(
                          topRight: Radius.circular(13),
                          bottomRight: Radius.circular(13))),
                ),
                const SizedBox(width: 3),
                Container(
                  width: 4,
                  height: 4,
                  decoration: BoxDecoration(
                    color: currentCategoryIndex == index
                        ? Colors.white
                        : Colors.transparent,
                    borderRadius: const BorderRadius.all(Radius.circular(3)),
                  ),
                ),
                const SizedBox(width: 5),
                Text(categoryModel.name ?? "",
                    style: TextStyle(
                        color: Colors.white,
                        fontSize: 14,
                        fontWeight: FontWeight.normal)),
              ],
            ),
          ),
        ),
        if (count > 0)
          Positioned(
            top: -5,
            right: -5,
            child: Container(
              width: 16,
              height: 16,
              decoration: const BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.all(Radius.circular(16))),
              child: Center(
                child: Text("$count",
                    style: TextStyle(color: Colors.white, fontSize: 12)),
              ),
            ),
          ),
      ],
    );
  }

  ///二级列表
  _buildPrompts() {
    return ListView.builder(
        itemCount: _magicPromptList.length,
        itemBuilder: (context, index) => _buildPromptsItem(index));
  }

  _buildPromptsItem(int index) {
    MagicPromptModel magicPromptModel = _magicPromptList[index];
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(magicPromptModel.name ?? "",
            style: TextStyle(
              color: Colors.white,
              fontSize: 14,
            )),
        const SizedBox(height: 12),
        _buildWrap(magicPromptModel.prompts),
        const SizedBox(height: 15),
      ],
    );
  }

  ///二级列表
  _buildWrap(List<PromptsModel>? prompts) {
    return Wrap(
      spacing: 8.0, // 主轴(水平)方向间距
      runSpacing: 8.0, // 纵轴（垂直）方向间距
      alignment: WrapAlignment.start, //沿主轴方向居中
      children: [
        ...prompts!.map((e) => _buildWrapItem(e)),

        // _buildWrapItem("All"),
        // ...mList.map((e) => _buildWrapItem("")),
      ],
    );
  }

  _buildWrapItem(PromptsModel promptModel) {
    return Stack(clipBehavior: Clip.none, children: [
      GestureDetector(
          onTap: () {
            setState(() {
              promptModel.selected = !promptModel.selected!;
              _getAllSelect();
            });
          },
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 16),
            height: 30,
            decoration: BoxDecoration(
                color: promptModel.selected!
                    ? const Color(0xFF608FF4)
                    : const Color(0xFF0C1A3D),
                borderRadius: const BorderRadius.all(
                  Radius.circular(4),
                )),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisSize: MainAxisSize.min,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  promptModel.prompt ?? "",
                  style: TextStyle(
                      color: Colors.white,
                      fontSize: 14,
                      fontWeight: FontWeight.bold),
                ),
              ],
            ),
          )),
      if (promptModel.selected!)
        Positioned(
            top: -5,
            right: -5,
            child: Image.asset(
              "assets/images/ic_tips_icon.png",
              width: 12,
            ))
    ]);
  }

  ///********************接口***********************
}
